package com.java.test.algorithm;

import java.util.Comparator;

/**
 * 冒泡排序
 *
 * @author骆昊
 *
 */
public class BubbleSorter implements Sorter {

    @Override
    public <T extends Comparable<T>> void sort(T[] list) {
        boolean swapped = true;
        for (int i = 1, len = list.length; i < len && swapped; ++i) {
            swapped = false;
            for (int j = 0; j < len - i; ++j) {
                if (list[j].compareTo(list[j + 1]) > 0) {
                    T temp = list[j];
                    list[j] = list[j + 1];
                    list[j + 1] = temp;
                    swapped = true;
                }
            }
        }
    }

    public static void main(String[] args) {
        BubbleSorter bubbleSorter = new BubbleSorter();
        Integer[] a = {9,6,1,3,4};
        bubbleSorter.sort(a);
        for(Integer t : a) {
            System.out.print(t);
            System.out.println(",");
        }
    }

//    @SuppressWarnings("unchecked")
//    public static <T extends Comparable<? super T>> void sort(List<T> list) {
//        list.sort(null);
//    }
//
//    @SuppressWarnings({"unchecked", "rawtypes"})
//    public static <T> void sort(List<T> list, Comparator<? super T> c) {
//        list.sort(c);
//    }


    @Override
    public <T> void sort(T[] list, Comparator<T> comp) {
        boolean swapped = true;
        for (int i = 1, len = list.length; i < len && swapped; ++i) {
            swapped = false;
            for (int j = 0; j < len - i; ++j) {
                if (comp.compare(list[j], list[j + 1]) > 0) {
                    T temp = list[j];
                    list[j] = list[j + 1];
                    list[j + 1] = temp;
                    swapped = true;
                }
            }
        }
    }
}
